import Taro, { Component } from '@tarojs/taro';
import { View, Image, Text, Button ,Form,Label,Input} from '@doctorwork/components';
// import DatePicker from '@vant/weapp/datetime-picker/index';
import { Picker } from '@tarojs/components';
import { connect } from '@tarojs/redux';
import Navigate from '../../components/Navigate/index';
import { rewriteAddMTA } from '../../model/utils/rewrite';
import SelectCar from '../../components/selectCar/index';
import { AtTextarea } from 'taro-ui';
import './index.styl';
import { timeFormat } from '../../model/utils/common';

@connect(({ record }) => ({
    ...record
}))
@rewriteAddMTA
export default class Record extends Component {
    constructor(props){
        super(props);
        this.state = {
            selected: 0,
            selectedStr: '停车费',
            selector:['停车费','过路费','保险费','违章罚款','汽车维修','汽车配饰','充电费','其他费用'],

        };
    }
    config = {
        navigationBarTitleText: '新增消费记录'
    };

    componentDidShow(){
        const _this = this;
        const {selector} = this.state;
        const id = this.$router.params.id;
        this.props.dispatch({
            type : 'record/init',
            payload: {id, callback: (detail)=>{
                _this.setState({
                    selected: detail.recordType,
                    selectedStr : selector[detail.recordType]
                });
            } }
        });
    }




    /**
     * 初始化数据
     * @param {*} province 
     */
    initData(id,province, location={}){
        const _this = this;
        const {selector} = this.state;
        this.props.dispatch({
            type : 'record/init',
            payload: {id,province,location, callback: (detail)=>{
                _this.setState({
                    selectedStr : selector[detail.recordType]
                });
            }}
        });
    }

    // 输入的值改变
    onInputChange(key,e){
        const {detail} = this.props;
        detail[key] = e.detail.value;
        this.props.dispatch({
            type : 'record/save',
            payload : {
                detail : {
                    ...detail
                },
            }
        });
    }
    validate(){
        const {price=0, desc,carNumber} = this.props.detail;
        if(!carNumber){
            return '请先添加车辆';
        }else if(price <= 0){
            return '金额输入有误';
        }else if(desc && desc.length > 40){
            return '备注不超过40个字符';
        }
        return null;
    }


    addCar(){
        this.props.dispatch({
            type : '$router/forward',
            payload : {
                url : '/pages/car/index',
            }
        });
    }
    /**
     * 切换日期
     * @param {*} e 
     */
    onDateChange(e){
        const time = e.target.value;
        const {detail} = this.props;
        this.props.dispatch({
            type : 'record/save',
            payload : {
                detail : {
                    ...detail,
                    time
                },
            }
        });
    }
    // 
    changeCarModal(carModal){
        const {isEdit} = this.props;
        if(!isEdit) return;
        this.props.dispatch({
            type : 'record/save',
            payload : {
                carModal
            }
        });
    }
    /**
     * 选中车辆
     * @param {*} carNumber 
     */
    onCarSelected(carNumber){
        this.props.dispatch({
            type: 'record/carNumberChange',
            payload: {
                carNumber
            }
        });
    }
    /**
     * 取消选择车辆
     */
    onCarCancel(){
        this.props.dispatch({
            type : 'record/save',
            payload : {
                carModal: false
            }
        });
    }
    /**
     * 数据变更
     * @param {*} type 
     * @param {*} value 
     */
    dataChange(type, value){
        // 更新类型
        const {detail} = this.props;
        detail[type] = value;
        this.props.dispatch({
            type : 'record/save',
            payload : {
                detail : {
                    ...detail
                },
            }
        });
    }
    /**
     * 缴费类型修改
     * @param {*} e 
     */
    typeChange(e){
        console.log('选择省份:',e);
        const index = e.detail.value;
        const {selector } = this.state;
        const selectedStr  =  selector[index];
        this.setState({selected: index, selectedStr });
        this.dataChange('recordType', index);
    }
    submit(){
        const valid = this.validate();
        if(valid){
            wx.showToast({
                icon: 'none',
                duration: 3000,
                title: valid
            });
        }else{
            this.props.dispatch({
                type : 'record/submit'
            });
        }
        
    }
    editMode(){
        this.props.dispatch({
            type: 'record/save',
            payload: {
                isEdit: true
            }
        });
    }
    deleteData(){
        const _this = this;
        wx.showModal({
            title: '提示',
            content: '确定要删除记录么？',
            success (res) {
                if (res.confirm) {
                    const {detail} = _this.props;
                    _this.props.dispatch({
                        type: 'record/delete',
                        payload: {
                            id: detail.id
                        }
                    });
                } else if (res.cancel) {
                    console.log('用户点击取消');
                }
            }
        });
          
        
    }
    
    render() {
        const {selected, selectedStr, selector} = this.state;
        const {detail,carModal,carList,isEdit} = this.props ;
        const endTime = timeFormat(Date.now()+86399,'YYYY-MM-DD');
        return (
            <View className='container'>
                <Navigate
                    title='日常记账'
                    color='black'
                    backgroundColor='white'
                    backTextColor='black'
                />
                <View className='oil-container'>
                    您爱车日常的每一笔消费都记录下来吧！ 目前支持 <Label className='record-type'>停车费、过路费、保险费、违章罚款、汽车维修、购买汽车配饰、充电费、其他费用</Label>等。
                </View>
                <View className='oil-container'>
                    {
                        carModal && <SelectCar carList={carList} carNumber={detail.carNumber} disabled={!isEdit}  onCarSelected={this.onCarSelected.bind(this)} onClose={this.onCarCancel.bind(this)} />
                    }
                    <View className='input-item'>
                        <Label className='item-title'><Label style='color:red'>*</Label>车辆: </Label>
                        {
                            detail.carNumber ? <Text className='add-car' onClick={this.changeCarModal.bind(this,true)} data-name={detail.carNumber}>{detail.carNumber}</Text> :
                                <Text className='add-car' onClick={this.addCar.bind(this)} data-name='点击添加车辆'>点击添加车辆</Text>
                        }
                        
                    </View>
                    <View className='input-item'>
                        <Label className='item-title'><Label style='color:red'>*</Label>时间: </Label>
                        <Label>
                            <View className='picker'>
                                {
                                    isEdit ? <Picker mode='date' onChange={this.onDateChange} disabled={!isEdit} value={detail.time} end={endTime}>
                                        {detail.time} <Text className='iconfont icon-right'>&#xe619;</Text>
                                    </Picker> : detail.time
                                }
                                
                            </View>
                        </Label>
                    </View>
                    <View className='input-item'>
                        <Label className='item-title'><Label style='color:red'>*</Label>类型: </Label>
                        {
                            isEdit ? <Picker mode='selector' value={selected} disabled={!isEdit} range={selector} onChange={this.typeChange}>
                                {selectedStr || '选择类型'} <Text className='iconfont icon-right'>&#xe619;</Text>
                            </Picker> : selectedStr
                        }
                        
                    </View>
                    <View className='input-item'>
                        <Label className='item-title'><Label style='color:red'>*</Label>金额(¥): </Label>
                        {
                            isEdit ? <Input
                                type='digit'
                                placeholder='请输入金额'
                                maxlength='11'
                                value={detail.price}
                                className='text-right'
                                disabled={!isEdit}
                                onInput={this.onInputChange.bind(this, 'price')}
                            /> : detail.price
                        }
                        
                    </View>
                    
                    <View className='input-item remark-content'>

                        <Label className='item-title'>备注: </Label>
                        <View className='remark-input'>
                            {
                                isEdit ? <AtTextarea
                                    type='digit'
                                    placeholder='不超过40个字符'
                                    value={detail.desc}
                                    maxLength={40}
                                    disabled={!isEdit}
                                    onChange={(data) => this.dataChange( 'desc',data )}
                                /> : detail.desc
                            }
                            
                        </View>
                    </View>
                    {/* <View className='input-item'>
                        <Label className='item-title'>上传图片: </Label>
                        <Input
                            type='digit'
                            placeholder='请输入加油金额'
                            maxlength='11'
                            value={detail.price}
                            className='text-right'
                            onInput={this.onInputChange.bind(this, 'price')}
                        />
                    </View> */}
                    
                </View>
                <View className='footer'>
                    

                    {
                        isEdit ?  <Button onClick={this.submit.bind(this)} className='oil-btn' data-name='保 存'>
                        保 存
                        </Button>: 
                            <View className='footer-flex'>
                                <Button onClick={this.deleteData.bind(this)} className='oil-btn-delete' data-name='删 除'>删 除</Button>
                                <Button onClick={this.editMode.bind(this)} className='oil-btn' data-name='编 辑'>编 辑</Button>
                            </View>
                    }
                </View>
            </View>

        );
    }
}
